// pages/card/card.js
const app = getApp()
var request = require("../../utils/request.js");
var util = require("../../utils/util.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    titleText: '停车电子卡',
    cardList: [{
      name: '月卡',
      money: '',
      time: '30',
      select: true
    },
    {
      name: '季卡',
      money: '',
      time: '120',
      select: false
    },
    {
      name: '年卡',
      money: '',
      time: '365',
      select: false
    },
    ],
    money: '',
    ruleType: 0,
    forbidShow: false, //禁停车是否显示
    freeCarShow: false, //免费车是否显示
    inputLen: 8,
    isFocus: true,
    carNo: '',
    translateSpace: 0,
    inputType: 1, // 车牌输入类型，1简称，2数字或者字母,
    popShow: false,
    carNumList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCardList();
    this.getCarNumList();
  },
  /**
   * 返回上一个页面
   */
  back() {
    wx.navigateBack({ //返回
      delta: 1,
      fail(err) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    })
  },
  /**
   * 选择会员卡
   * @param {*} e 
   */
  checkCard(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let cardList = that.data.cardList;
    let money = that.data.money;
    for (let i = 0; i < cardList.length; i++) {
      if (i == index) {
        cardList[i].select = true

      } else {
        cardList[i].select = false
      }
    }
    if (index == 0) {
      money = cardList[index].money + '元/月'
    } else if (index == 1) {
      money = cardList[index].money + '元/季'
    } else {
      money = cardList[index].money + '元/年'
    }
    that.setData({
      cardList: cardList,
      money: money,
      ruleType: index
    })
  },
  /**
   * 获取电子卡
   */
  getCardList() {
    let that = this;
    let url = "/api/cUser/selectAllEleCard";
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let card = res.data.data;
          let cardList = that.data.cardList;
          cardList[0].money = card[0].monthAmount;
          cardList[1].money = card[0].quarterAmount;
          cardList[2].money = card[0].yearAmount;
          let money = cardList[0].money + '元/月'
          that.setData({
            cardList: cardList,
            card: card,
            money: money
          })
        } else {
          Toast(res.data.message);
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 开通电子卡
   */
  openCard() {
    let that = this;
    var startTime = util.formatDate(new Date());
    let index = that.data.ruleType;
    let cardList = that.data.cardList;
    let card = that.data.card;
    let userId = wx.getStorageSync('userId');
    let ruleId = card[index].ruleId;
    let body = '购买电子卡';
    let totalFee = cardList[index].money;
    let carCardNum = that.data.carNo;
    let url = "/api/pay/elecardMiniPayV2?uid=" + userId + "&body=" + body + "&ruleId=" + ruleId + "&duration=0" + "&totalFee=" + totalFee + "&CarCardNum=" + carCardNum + "&startTime=" + startTime + "&type=0";
    request.http(url, 'POST')
      .then((res) => {
        wx.hideLoading();
        if (res.data.code == 200) {
          that.forbidShowClose();
          let body = res.data.data;
          //支付
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
            nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
            package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
            signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
            paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
            success: function (res) { // 成功后的回调函数
              Toast.success('开通成功');
              wx.redirectTo({
                url: '../grade/grade'
              })
            },
            fail(res) { }
          })

        } else {
          Toast.fail('开通失败');
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '开通失败',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 车牌号弹窗关闭
   */
  forbidShowClose() {
    this.setData({
      forbidShow: false,
      carNo: '',
      translateSpace: 0,
      showPlateInput: false
    })
  },
  /**
   * 输入手机号弹窗打开
   */
  showforbidShow() {
    this.setData({
      forbidShow: true
    })
    this.onFocus();
  },
  /**
   * 设置输入框值
   * @param {*} e 
   */
  setValue: function (e) {
    var that = this;
    that.setData({
      iptValue: e.detail.value
    });
  },
  //
  /**
   * 自定义键盘点击
   * @param {*} e 
   */
  inputChange(e) {
    let that = this;
    let iptValue = that.data.iptValue;
    let value = e.detail;
    let keyBoardType = that.data.keyBoardType;
    that.setData({
      iptValue: iptValue + value
    })
    if (keyBoardType == 1) {
      that.setData({
        keyBoardType: 2
      })
    }
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType: inputType
    })
  },
  /**
   * 键盘输入操作
   * @param {*} e 
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确的车牌号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1
    })
  },
  /**
   * 用于键盘输入删除
   * @param {*} e 
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
    })
  },
  /**
   * 判断车牌号
   * @param {String} value 车牌号
   */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 输入车牌号
   * @param {*} e 
   */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }

    that.setData({
      showPlateInput: true,
      inputType: inputType
    });
  },
  /**
   * 查询车牌列表
   */
  getCarNumList() {
    let that = this;
    let userId = wx.getStorageSync('userId');
    let url = "/api/cCarMessage/getCarByUserId?userId=" + userId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let list = res.data.data;
          if (list != null && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i].select = true
              } else {
                list[i].select = false
              }
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },
  /**
   * 弹窗展示
   */
  showPop() {
    this.setData({
      popShow: true
    })
  },
  /**
   * 关闭弹窗
   */
  popShowClose() {
    this.setData({
      popShow: false
    })
  },
  /**
   * 选择不同的弹窗弹起
   */
  checkPop() {
    let that = this;
    let carNumList = that.data.carNumList;
    if (carNumList != null && carNumList.length > 0) {
      that.showPop();
    } else {
      that.showforbidShow();
    }
  },
  /**
   * 选择车牌号
   * @param {*} event 
   */
  carNumCheck(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let carNumList = that.data.carNumList;
    for (let i = 0; i < carNumList.length; i++) {
      if (i == index) {
        carNumList[i].select = true
      } else {
        carNumList[i].select = false
      }
    }
    that.setData({
      carNo: carNumList[index].carCardNum,
      carNumList: carNumList
    })
  },
  /**
   * 获取车牌号
   */
  getCarNumberList() {
    let that = this;
    let carNo = ''
    let carNumList = that.data.carNumList;
    for (let i = 0; i < carNumList.length; i++) {
      if (carNumList[i].select) {
        carNo = carNumList[i].carCardNum
      }
    }
    that.setData({
      carNo: carNo
    })
    this.popShowClose();
    this.openCard();
  },
  //支付回调
  // payCallBack(body) {
  //   let that = this;
  //   let userId = wx.getStorageSync('userId');
  //   let user = body.user;
  //   let url = "/api/pay/wechat/eleCardCallback";
  //   var params = body;
  //   request.http(url, 'POST', params)
  //     .then((res) => {
  //       wx.hideLoading();
  //       if (res.data.status == 200) {
  //         Toast.success('开通成功');
  //         user = JSON.stringify(user);
  //         wx.redirectTo({
  //           url: '../grade/grade?user=' + encodeURIComponent(user),
  //         })
  //       } else {
  //         Toast.fail('支付回调失败');
  //       }
  //     })
  // },
  /**
   * 绑定车牌号
   */
  bindCarNumber() {
    let that = this;
    let carNo = that.data.carNo;
    let userId = wx.getStorageSync('userId');
    if (!that.isCarPlate(that.data.carNo)) {
      Toast('请输入正确车牌号');
      return;
    }
    let url = "/api/cUser/bindCarNum?carNum=" + carNo + "&userId=" + userId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          Toast.success('绑定成功');
          that.openCard();
        } else {
          Toast.fail(res.data.message);
        }
      }).catch((errMsg) => {
        // wx.showToast({
        //   title: '网络错误',
        //   icon: 'loading',
        //   duration: 1500,
        // })
      });
  }
})